package com.szsh.aiot.hsm.thirdService;


import com.google.gson.Gson;
import com.szsh.aiot.hsm.dto.mkreport.MKReportRequest;
import com.szsh.aiot.hsm.dto.mkreport.MKReportResponse;
import com.szsh.aiot.hsm.dto.mkreport.Macs;
import com.szsh.aiot.hsm.utils.AESUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;


/**
 * 迈科设备上报接口
 */
@Component
public class MkReportClient {

    private static final Logger LOGGER = LoggerFactory.getLogger(MkReportClient.class);

    @Value("${hsm.mkreport.endpoint}")
    private String url;

    @Value("${hsm.mkreport.partner-key}")
    private String partnerKey;

    @Value("${hsm.mkreport.partner-id}")
    private String partnerID;

    @Autowired
    private RestTemplate restTemplate;

    Gson gson = new Gson();

    public MKReportResponse mkReport(String mac, String type, String action) {
        MKReportResponse response = new MKReportResponse();
        try{
            MKReportRequest req = new MKReportRequest();
            Macs macinfo = new Macs();
            macinfo.setType(type);
            macinfo.setAction(action);
            Map<String, Macs> map = new HashMap<>();
            map.put(mac, macinfo);
            String macs = gson.toJson(map);
            Long tamp = System.currentTimeMillis();
            String iv = partnerID + tamp;
            String encryptResultStr = AESUtil.encrypt(macs, partnerKey, iv);
            req.setMacs(encryptResultStr);
            req.setTimestamp(tamp);
            LOGGER.info("MKReport Req[{}]", req.toString());
            String rsp = restTemplate.postForObject(url, req, String.class);
            LOGGER.info("MKReport Rsp[{}]", rsp);
            response= gson.fromJson(rsp,MKReportResponse.class);
        }catch (Exception e){
            response.setCode(-1);
            LOGGER.error("调用迈科上报接口异常{}",e);
        }
        return response;
    }


}
